// pages/goods/pendingOrder/pendingOrder.js
import Data from "../../../utils/data";
import util from '../../../utils/utils';
import User from '../../../utils/user';
import Dialog from '../../../dist/dialog/dialog';
import {
  CartHttp
} from '../../../api/cart.js'

const cartModel = new CartHttp();
let remindSelfLife = util.cache_get('remind_self_lift', false);
Page({
  /**12
   * 页面的初始数据
   */
  autoAuth: true,
  payComponentEl: null,
  quickPayBox: false,
  type:2,
  isGift:0,
  involvementPea:0,
  data: {
    type:2,
    initUser: true,
    openLogin: false,
    isLoading: false,
    discountSummaryList: [],
    isShowPayBox: false,
    userInfo: User.UserData,
    pwdVal: '', //输入的密码
    payFocus: true, //文本框焦点
    isCheckeNotPwd: User.UserData.hasOwnProperty('common') ? User['UserData']['common']['pass_noneed'] : false, // 是否开通免密支付
    isSelfLifting: false, // 是否选择自提
    isCheckedProtocol: false, // 是否选择到店自取协议
    isSeductionFare: false, // 是否幸运豆抵扣
    paymentMethod: 3, // 支付方式
    remark: '', // 备注
    isRemind: remindSelfLife, //是否不提醒自提弹框
    isShowSelfLiftingPopup: false, // 是否显示自提确认弹出层
    isShowPaymentPopup: false, // 是否显示支付方式显示弹出层
    isShowChooseStore: false, // 自提点弹窗
    isShowReceiveTime: false, //是否显示配送时间选择显示弹窗层
    isShowPay: false, //输入支付密码弹出层
    checkedIcon: {
      active: '/images/icon/icon_check_active.png',
      normal: '/images/icon/icon_check_inactive.png',
      normalEmpty: '/images/icon/icon_check_inactive_empty.png'
    },
    couponRes: {
      total_count: 0,
    },
    couponData: [],
    couponId: 0,
    address: {
      areaInfo: '',
      address: ''
    },
    addressId: 0,
    orderInfo: {},
    store: {},
    storeInfo: false,
    StoreList: [],
    goods: [],
    cartID: [],
    goodsList: [],
    goodsType: 1,
    priceInfo: {
      discountAmount: 0,
      rawOrderMoney: 0,
      realOrderMoney: 0,
      carriage: 0,
      deductLuckyBeans: 0,
      deduction: 0,
      packingFee: 0
    },
    CreateOrder: false,
    requestDiscount: {
      couponId: 0,
      useRecommendCoupon:1,
      dispatchType: 2,
      goods: [{
        "skuAmount": 0,
        "skuId": 0,
        "spuId": 0
      }],
      luckyBean: 0,
      payType: 4,
      storeId: 0,
      userId: 0,
      orderSourceType:1,
      addressId:0
    },
    receiveProtocol: {
      "name": "到店自提协议",
      "path": util.pageUrl + "copyright/receive_protocol.html",
      "downUrl": "",
      "version": 2
    },
    deliveryDate: '',
    deliveryDateText: '',
    deliveryToDay: '',
    deliveryTime: '',
    receiveTime: [],
    receiveTitleText: '取货时间',
    receiveTitle: '选择取货时间',
    tipTitle: '',
    tipDesc: '订单确认后将无法修改',
    activeDay: '',
    activeTime: '',
    latitude: 0,
    longitude: 0,
    discountStat: true,
    storeServiceId:0,
    isSelectPickupName:false,
    isSelectAddress:false,
    setStoreInfo:{},
  },
  onPullDownRefresh: function () {
    this.initData();
  },

  initPage: function (options) {
    let app = getApp();
    this.payComponentEl = this.selectComponent('#payBox');
    let self = this;
    let setData;
    wx.hideShareMenu();
    if(options.hasOwnProperty('involvementPea')){
      self.involvementPea = options['involvementPea'];
      self.type = 2;
      self.setData({
        'requestDiscount.luckyBean': 0,
        'requestDiscount.dispatchType':2,
        isSeductionFare:false,
        type:2,
      });
    }
    if(options.hasOwnProperty('type')){
      self.type = util.fixInt(options['type']);
      setData = {
        'requestDiscount.luckyBean': 0,
        'requestDiscount.dispatchType':2,
        type:self.type,
      };
      if(self.type === 3){
        setData['isSeductionFare'] = false;
        setData['requestDiscount.dispatchType'] = 2;
        setData['requestDiscount.orderSourceType'] = 2;
      }
      self.setData(setData);
    }
    if(options.hasOwnProperty('isGift')){
      self.isGift = util.fixInt(options['isGift']);
    }
    console.log(options);
    self.initData();
    /**
     * 获取页面配置
     */
    if (app.globalData.pageConfig.receiveProtocol) {
      this.setData({
        receiveProtocol: app.globalData.pageConfig.receiveProtocol
      });
    }
  },
  initData: function () {
    let type = 1;
    let options = this.options;
    let id = [];
    let goods = [];
    let cartID    = [];
    let param     = {};
    let storeId   = 0;
    let serviceId = 0;
    let couponId = 0;
    let self      = this;
    if (options.hasOwnProperty('type')) {
      type = util.fixInt(options.type);
    }
    if (options.hasOwnProperty('id')) {
      id = JSON.parse(decodeURIComponent(options.id));
    }
    if (options.hasOwnProperty('storeId')) {
      storeId = util.fixInt(options.storeId);
    }
    if (options.hasOwnProperty('serviceId')) {
      serviceId = util.fixInt(options.serviceId);
    }
    if (options.hasOwnProperty('couponId')) {
      couponId = util.fixInt(options.couponId);
    }
    if (!id) {
      util.msg('商品数据错误！');
      setTimeout(function () {
        wx.navigateBack();
      }, 400);
      return false;
    }
    if (!serviceId) {
      util.msg('下单参数错误-001！');
      setTimeout(function () {
        wx.navigateBack();
      }, 400);
      return false;
    }
    for (let i = 0; i < id.length; i++) {
      if (id[i].hasOwnProperty('cart_id')) {
        cartID.push(id[i]['cart_id']);
      }
      console.log(id[i])
      goods.push({
        skuId: id[i]['sku_id'],
        spuId: id[i]['spu_id'],
        skuAmount: id[i]['amount']
      });
    }
    this.setData({
      goods: goods,
      cartID: cartID,
      serviceId: serviceId,
      'requestDiscount.storeId': storeId,
      'requestDiscount.goods': goods,
      'requestDiscount.userId': User.UserData['uid'],
      'requestDiscount.couponId':couponId
    });
    param = this.data.requestDiscount;
    param.latitude = this.data.latitude;
    param.longitude = this.data.longitude;
    if (this.data.latitude > 0) {
      param.loadAddress = 0;
    } else {
      param.loadAddress = 1;
    }
    //更新用户资料
    this.getUserInfo(function (userInfo) {
      self.setData({
        userInfo: userInfo
      });
      if(self.data.type === 2){
        //获取默认收货地址
        self.getMyAddress(function () {
          self.selectGoods();
        });
      }else{
        //获取自提点列表；
        self.getStoreList(function () {
          self.selectGoods();
        });
        //获取默认收货地址
        self.getMyAddress();
      }
    }, function () {
      self.setData({
        initUser:false
      });
    }, true);
  },
  /**
   * 获取门店自提点列表
   */
  getStoreList: function (callback) {
    let self       = this;
    let service_id = this.data.serviceId;
    let success   = function (res,callback) {
      util.request({
        url: '/yddgoods/ServiceCorePickupV2',
        data: {
          lat: res.latitude,
          lng: res.longitude,
          hardware: 1,
          "store_service_id": service_id,
          "page": 1,
          "page_size": 30
        },
        handle: true,
        loading: false,
        callback: function (result) {
          let default_store = {};
          let setData = {};
          let item;
          let servicePointInfo = wx.getStorageSync('servicePointInfo_2');
          let pointId = 0;
          let isDefaultFlag = false;
          if(servicePointInfo && servicePointInfo.hasOwnProperty('pointId')){
            pointId = servicePointInfo['pointId'];
          }
          if(result.res['pickups'].length === 0){
            util.msg('获取自提点列表失败，下拉再试试吧！');
          }
          for (let i = 0; i < result['res']['pickups'].length; i++) {
            //计算距离
            item = result['res']['pickups'][i];
            let distance = result['res']['pickups'][i]['distance'];
            item = result['res']['pickups'][i];
            if (distance < 1000) {
              distance = distance + ' m';
            }
            if (distance > 1000) {
              distance = util.fixFloat(distance / 1000) + ' km';
            }
            if(item['start_time'] === 0 && item['fetch_business_hours'].length > 0){
              item['startDate'] = item['fetch_business_hours'][0];
            }else{
              item['startDate'] = util.formatTime('HH:mm', item['start_time'])
            }
            if(item['end_time'] === 0 && item['fetch_business_hours'].length > 0){
              item['endDate'] = item['fetch_business_hours'][item['fetch_business_hours'].length-1];
            }else{
              item['endDate'] = util.formatTime('HH:mm', item['end_time'])
            }
            result['res']['pickups'][i]['distance']  = distance;
            result['res']['pickups'][i]['startDate'] = item['startDate'];
            result['res']['pickups'][i]['endDate']   = item['endDate'];
            if(pointId > 0 && pointId === item['id']){
              default_store = item;
              isDefaultFlag = true;
            }
          }
          if (!isDefaultFlag && result.res['pickups'].length > 0) {
            default_store = result.res['pickups'][0];
          }
          if(result.res['pickups'].length === 0){
            util.msg('获取自提点列表失败，下拉再试试吧！');
          }
          setData['StoreList'] = result.res['pickups'];
          if(self.data.requestDiscount.dispatchType === 1){
            setData['tipTitle'] = '是否前往【'+default_store.pickup_name+'】自提？';
            setData['tipDesc'] = '订单确认后将无法修改';
          }
          if(!self.data.storeInfo){
            setData['storeInfo'] = default_store;
            setData['latitude']  = default_store.latitude;
            setData['longitude'] = default_store.longitude;
          }
          self.setData(setData);
          callback && callback();
        }
      });
    };
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        success({
          latitude: res.latitude,
          longitude: res.longitude
        },callback);
      },
      fail(res) {
        success({
          latitude: 0,
          longitude: 0
        },callback);
      }
    });
  },
  /**
   * 获取默认收货地址
   */
  getMyAddress: function (callback) {
    let self = this;
    Data.ActiveAddr({
      store_id: this.data.store_id
    }, function (result) {
      if (Object.keys(result.res.addr).length > 0) {
        result.res.addr['areaInfo'] = util.formatAreaToString(result.res.addr, '', 2);
        let setData = {
          address: result.res.addr,
          addressId: result.res.addr.addr_id,
          'requestDiscount.addressId': result.res.addr.addr_id
        };
        if (self.data.requestDiscount.dispatchType === 2 && result.res.addr.hasOwnProperty('latitude')) {
          setData['latitude']  = result.res.addr.latitude;
          setData['longitude'] = result.res.addr.longitude;
        }
        self.setData(setData);
      }
      callback && callback(result.res.addr);
    })
  },
  /**
   * 获取提货时间列表
   * @param orderMoney
   */
  getOrderCarriage(orderMoney) {
    let self = this;
    util.request({
      url: '/order/carriage',
      isJava: true,
      data: {
        latitude: self.data.latitude,
        longitude: self.data.longitude,
        goodsType: self.data.goodsType,
        money: orderMoney,
        dispatchType: self.data.requestDiscount.dispatchType,
        storeId: self.data.requestDiscount.storeId
      },
      callback: function (result) {
        self.setData({
          activeDay: result['res'][0]['date'],
          deliveryDate: result['res'][0]['date'],
          deliveryDateText: result['res'][0]['date'],
          deliveryToDay: result['res'][0]['dispalyDate'],
          receiveTime: result['res']
        });
      }
    });
  },
  /**
   * 选择收货地址
   * @param _detail
   */
  upAddress(_detail) {
    _detail['areaInfo'] = util.formatAreaToString(_detail, '', 2);
    let setData = {
      address: _detail,
      addressId: _detail.addr_id,
      'requestDiscount.addressId': _detail.addr_id
    };
    if (_detail.hasOwnProperty('latitude')) {
      setData['latitude']  = _detail.latitude;
      setData['longitude'] = _detail.longitude;
    } else {
      setData['latitude'] = 0;
      setData['longitude'] = 0;
    }
    setData['tipTitle'] = '是否配送到【'+_detail.detailInfo+'】？';
    setData['tipDesc'] = '订单确认后，将无法再修改配送地址哦';

    this.setData(setData);
    this.selectGoods();
  },
  upRemark(_detail) {
    this.setData({
      remark: _detail
    });
  },
  // 切换配送方式
  onChangePickupWay ({ detail }) {
    let dispatchType = 1; // 自提
    let setData = {};
    let address = {};
    let tipAddress = '';
    if (detail) {
      if(this.data.address.address){
        tipAddress = this.data.address.detailInfo;
      }
      dispatchType = 2; // 配送
      setData['receiveTitleText'] = '配送';
      setData['receiveTitle']     = '选择送达时间';
      setData['tipTitle']         = '是否配送到 【'+tipAddress+'】？';
      setData['tipDesc']          = '订单确认后，将无法再修改配送地址哦';
      address = this.data.address;
    } else {
      setData['receiveTitleText'] = '取货';
      setData['receiveTitle']     = '选择取货时间';
      setData['tipTitle']         = '是否前往【'+this.data.storeInfo.pickup_name+'】自提？';
      setData['tipDesc']          = '订单确认后将无法修改';
      address = this.data.storeInfo;
    }
    setData['requestDiscount.dispatchType'] = dispatchType;
    if (address.hasOwnProperty('latitude')) {
      setData['latitude']  = address.latitude;
      setData['longitude'] = address.longitude;
    } else {
      setData['latitude']  = 0;
      setData['longitude'] = 0;
    }
    this.setData(setData);
    this.selectGoods();
  },
  // 到店自取协议
  onChangeProtocol(event) {
    this.setData({
      isCheckedProtocol: event.detail
    });
    // util.cache_put('receiveProtocol', "1");
  },
  //是否免密
  onChangeNotPwd(event) {
    this.setData({
      isCheckeNotPwd: event.detail
    });
  },
  // 幸运豆抵扣运费
  onChangeSeductionFare({detail}) {
    let luckyBean = 0;
    if (detail) {
      luckyBean = 1
    }
    this.setData({
      isSeductionFare: detail,
      'requestDiscount.luckyBean': luckyBean,
    });
    this.selectGoods(2);
  },

  onClosePay() {
    this.setData({
      isShowPay: false
    })
  },
  // 支付方式弹出层 - 显示
  onShowPayment() {
    this.setData({
      isShowPaymentPopup: true
    })
  },
  // 支付方式弹出层 - 关闭
  onClosePayment() {
    this.setData({
      isShowPaymentPopup: false
    });
  },
  // 支付方式弹出层 - 确认
  onConfirmPayment(event) {
    let payment = util.fixInt(event.detail.payment);
    if (payment !== 4) {
      Dialog.confirm({
        message: '使用非会员卡支付\n将无法享受所有会员折扣',
        confirmButtonText: "继续支付",
        cancelButtonText: "暂时放弃"
      }).then(() => {
        this.setData({
          isShowPaymentPopup: false,
          paymentMethod: payment,
          'requestDiscount.payType': payment,
        });
        this.selectGoods()
      }).catch(() => {
        this.setData({
          isShowPaymentPopup: false,
        });
      });
    } else {
      this.setData({
        isShowPaymentPopup: false,
        paymentMethod: payment,
        'requestDiscount.payType': payment,
      });
      this.selectGoods()
    }
  },
  onShowReceiveTime(event) {
    if (this.data.activeTime === '') {
      this.setData({
        activeTime: this.data.receiveTime[0]['timeList'][0]['time']
      });
    }
    this.setData({
      isShowReceiveTime: true
    });
  },
  onCloseReceiveTime(event) {
    this.setData({
      isShowReceiveTime: false
    });
  },
  onConfirmReceiveTime(event) {
    let self = this;
    this.setData({
      deliveryToDay: event.detail.displaydate,
      deliveryTime: event.detail.time,
      deliveryDate: event.detail.day
    });
    if (this.quickPayBox === true) {
      this.quickPayBox = false;
      setTimeout(function () {
        self.paySubmit();
      }, 500)
    }
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail
    });
  },
  /**
   * 选取优惠券
   */
  chooseCoupon: function (e) {
    let data = e.currentTarget.dataset;
    let id   = data.id;
    let rec  = 0;
    if (this.data.couponId === id) {
      id  = 0;
      rec = 0;
    }
    this.setData({
      couponId: id,
      'requestDiscount.couponId': id,
      'requestDiscount.useRecommendCoupon': rec
    });
    this.selectGoods();
  },
  onShowChooseStore: function () {
    this.setData({
      isShowChooseStore: true
    });
  },
  onCloseStores: function () {
    this.setData({
      isShowChooseStore: false
    });
  },
  /**
   * 选取自提点
   */
  chooseStores: function (e) {
    let id        = e.detail;
    let StoreList = this.data.StoreList;
    let default_store = {};
    if(id === this.data.storeInfo.id){
      return true;
    }else{
      let setData = {};
      for (let i = 0; i < StoreList.length; i++) {
        if (StoreList[i]['id'] === id) {
          default_store = StoreList[i];
        }
      }
      setData['isShowSelfLiftingPopup'] = false;
      setData['storeInfo'] = default_store;
      setData['setStoreInfo'] = {};
      setData['latitude'] = default_store.latitude;
      setData['longitude'] = default_store.longitude;
      setData['tipTitle'] = '是否前往【'+default_store.pickup_name+'】自提？';
      setData['tipDesc'] = '订单确认后将无法修改';
      this.setData(setData);
      this.selectGoods();
    }
  },
  /**
   *去支付
   */
  paySubmit: function () {
    let self = this;
    let _data = self.data;
    let isRemind  = this.data.isRemind;
    let isSelectPickupName  = this.data.isSelectPickupName;
    let isSelectAddress  = this.data.isSelectAddress;
    _data.requestDiscount.dispatchType = util.fixInt(_data.requestDiscount.dispatchType);
    if (_data.requestDiscount.dispatchType === 1) {
      if(!isRemind && !isSelectPickupName){
        self.setData({
          isShowSelfLiftingPopup: true,
        });
        return false;
      }
      if (_data.address.address === '') {
        util.msg('请设置收货人信息!');
        setTimeout(function () {
          util.toPage('/pages/me/address/manage/manage');
        },300);
        return false;
      }
      if (_data.deliveryTime === '') {
        self.quickPayBox = true;
        // util.msg('请选择取货时间!');
        self.onShowReceiveTime();
        return false;
      }
      // if (!_data.isCheckedProtocol) {
      //   util.msg('请阅读《到店自取协议》!');
      //   return false;
      // }
    }
    if (_data.requestDiscount.dispatchType === 2) {
      if (_data.address.address === '') {
        util.msg('请选择收货地址!');
        setTimeout(function () {
          util.toPage('/pages/me/address/manage/manage');
        },300);
        return false;
      }
      if(_data.type === 1 && !isRemind && !isSelectAddress){
        self.setData({
          isShowSelfLiftingPopup: true,
        });
        return false;
      }
      if (_data.type === 1 && _data.deliveryTime === '') {
        // util.msg('请选择配送时间!');
        self.quickPayBox = true;
        self.onShowReceiveTime();
        return false;
      }
    }
    if(_data.type !== 1){
      self.setData({
        deliveryTime:'00:00',
      });
    }
    if (_data.paymentMethod !== 4) {
      this.createOrder();
    } else {
      let cardBlance = util.formatMoney(_data.userInfo.common.card_blance, 2);
      let OrderMoney = _data.priceInfo.realOrderMoney;
      if (cardBlance < OrderMoney) {
        util.msg('会员卡余额不足，请更换支付方式');
      } else {
        this.createOrder();
      }
    }
  },
  /**
   * 获取优惠结果信息
   * @param t
   */
  selectGoods: function (t) {
    let self  = this;
    let param = self.data.requestDiscount;
    let type  = t || 1;
    param.latitude  = this.data.latitude;
    param.longitude = this.data.longitude;
    if (param.latitude > 0) {
      param.loadAddress = 0;
    } else {
      param.loadAddress = 1;
    }
    util.request({
      url: 'order/discount',
      isJava: true,
      data: param,
      callback: function (result) {
        let setData;
        let res       = result.res;
        let skuList   = res.skuList;
        let goodsList = [];
        let cardBalance = self.data.userInfo.common.card_blance;
        wx.stopPullDownRefresh();
        for (let i = 0; i < skuList.length; i++) {
          goodsList.push(skuList[i]);
        }
        let discountSum = [];
        for(let ds in res.discountSummaryList){
          discountSum.push(res.discountSummaryList[ds]);
        }
        setData = {
          discountStat: true,
          discountSummaryList: discountSum,
          priceInfo: {
            discountAmount: util.formatMoney(res.discountAmount),
            rawOrderMoney: util.formatMoney(res.rawOrderMoney),
            realOrderMoney: util.formatMoney(res.realOrderMoney),
            carriage: util.formatMoney(res.carriage),
            deductLuckyBeans: res.deductLuckyBeans,
            deduction: util.formatMoney(res.deduction),
            packingFee: util.formatMoney(res.packingFee)
          },
          goodsList: goodsList,
          goodsType: res.goodsType,
          serviceId:res.storeServiceId,
        };
        if(res.availableCoupons){
          let couponData = res.availableCoupons ? res.availableCoupons : [];
          for(let i=0;i<couponData.length;i++){
            if(couponData[i].discountType === 2){
              couponData[i]['rebate'] = 100 - couponData[i]['rebate'] * 100;
            }
          }
          if(couponData){
            setData['couponData'] = couponData;
          }
        }
        if(type === 1){
          setData['deliveryTime'] = '';
        }
        console.log(cardBalance,res.realOrderMoney);
        if (cardBalance < res.realOrderMoney) {
          setData['paymentMethod'] = 3;
        }
        if (res.usedProductCouponId) {
          self.couponId = res.usedProductCouponId;
          setData['couponId'] = res.usedProductCouponId;
          setData['requestDiscount.couponId'] = res.usedProductCouponId;
        }
        if (result.code > 0) {
          //停用点击
          setData['discountStat'] = false;
          self.setData(setData);
          setTimeout(function () {
            util.msg(result.msg);
          }, 500);
        } else {
          /**
           * 获取配送、自提时间列表
           */
          self.setData(setData);
          self.getOrderCarriage(res.realOrderMoney);
        }
      }
    });
  },
  onConfirmPwd: function (e) {
    // console.log(e);
    this.sendOrder(e.detail.pay_key);
  },
  createOrder: function (e) {
    if (this.data.paymentMethod === 3) {
      this.sendOrder();
    } else {
      if (this.data.userInfo['common']['pass_noneed'] === false) {
        this.payComponentEl.setHandleType(2);
        this.openPayBox('');
      } else {
        this.sendOrder();
      }
    }
  },
  sendOrder: function (pay_key) {
    let self    = this;
    let _data   = self.data;
    let key     = pay_key || '';
    let channel = User.getShareParam(0);
    let address = _data.address['areaInfo'] + _data['address']['address'];
    if (_data.requestDiscount.dispatchType === 1) {
      // 自提
      address = util.formatAreaToString(_data.storeInfo,'') + _data.storeInfo['area'] + _data.storeInfo['store_address'];
      _data.requestDiscount.servicePointId = _data.storeInfo.id;
      _data.requestDiscount.addressId = 0;
    }else{
      _data.requestDiscount.addressId = this.data.addressId;
    }
    if(channel.ekey){
      _data.requestDiscount.ekey = channel.ekey;
    }else{
      _data.requestDiscount.ekey = '';
    }
    if(channel.shareUid){
      if(channel.shareUid != this.userInfo.uid){
        _data.requestDiscount.shareUid = channel.shareUid;
      }else{
        _data.requestDiscount.shareUid = '';

      }
    }else{
      _data.requestDiscount.shareUid = '';
    }
    self.setData({
      'requestDiscount.cartIds': _data.cartID.join(','),
      'requestDiscount.address': address,
      'requestDiscount.ekey': _data.requestDiscount.ekey,
      'requestDiscount.shareUid': _data.requestDiscount.shareUid,
      'requestDiscount.phoneNumber': _data.address.phone_number,
      'requestDiscount.receiveName': _data.address.user_name,
      'requestDiscount.dispatchTime': _data.deliveryDate + " " + _data.deliveryTime,
      'requestDiscount.remark': _data.remark,
      'requestDiscount.clientType': 3,
      'requestDiscount.payType': _data.paymentMethod
    });
    if(self.isLoading === true){
      return false;
    }
    console.log('type',self.type);
    self.isLoading = true;
    if (_data.CreateOrder === false) {
      let func = 'createOrder';
      // if(self.type === 2){
      //   func = 'createRushOrder';
      //   _data.requestDiscount['involvementPea'] = self.involvementPea;
      // }
      if(self.type === 3){
        _data.requestDiscount['orderSourceType'] = 2;
      }
      if(self.isGift === 1){
        _data.requestDiscount['orderSourceType'] = 3;
      }
      cartModel[func](_data.requestDiscount).then((res) => {
        self.isLoading = false;
        util.msg('下单成功');
        self.isLoading = false;
        this.setData({
          orderInfo:res,
          CreateOrder: res.unionOrderId
        });
        if(res.hasOwnProperty('status') && util.fixInt(res.status) === 1){
          this.payComplete({
            detail:{
              status:'complete'
            }
          });
          return false;
        }
        this.payComponentEl.setOrderID(res.unionOrderId);
        if (_data.paymentMethod === 3) {
          this.openPayBox(res.unionOrderId);
        } else {
          this.payComponentEl.requestPay(pay_key);
        }
      }).catch((res)=>{
        self.isLoading = false;
        if(res.code === 3005){
          setTimeout(function () {
            util.toPage('/pages/me/address/manage/manage');
          },500);
        }
      });
    } else {
      this.openPayBox(this.data.CreateOrder);
    }
  },
  openPayBox: function (order_id) {
    this.setData({
      isShowPayBox: true,
    });
    this.payComponentEl.switchPayment(util.fixInt(this.data.paymentMethod));
    this.payComponentEl.setShowPayTime(true);
    this.payComponentEl.setOrderID(order_id);
    this.payComponentEl.startPayBox();
  },
  payComplete: function (res) {
    let self = this;
    self.setData({
      isShowPayBox: false,
    });
    console.log(res);
    let url = '';
    if(self.data.orderInfo.hasOwnProperty('freeOrderEnable') && self.data.orderInfo['freeOrderEnable'] === 2){
      res.detail.status = 'goto';
    }
    if (res.detail.status === 'complete') {
      url = '/pages/goods/paySuccess/paySuccess?id='+self.data.CreateOrder
    }else{
      url = '/pages/me/yddorder/index?type=' + self.data.requestDiscount.dispatchType;
      // if(self.type === 2){
      //   url = '/pages/order/seckillOrder/seckillOrder?t=1';
      // }
    }
    // url = '/pages/me/yddorder/index?type=' + self.data.requestDiscount.dispatchType;

    setTimeout(function () {
      util.toPage(url, false, true);
    }, 300);
  },
  onSwitchPayMethod: function (e) {
    let data = e.currentTarget.dataset;
    let type = parseInt(data['type']);
    this.setData({
      isShowPaymentPopup: false,
      paymentMethod: type,
      'requestDiscount.payType': type,
    });
    this.selectGoods(2);
  },
  // 自提弹出层 - 关闭
  onCloseSelfLifting(e) {
    if (e.detail === true) {
      util.cache_put('remind_self_lift', e.detail);
    }
    this.setData({
      isRemind: e.detail,
      isShowSelfLiftingPopup: false
    });
  },
  // 自提弹出层 - 确认
  onConfirmSelfLifting(e) {
    let self = this;
    let setData = {};
    if (e.detail === true) {
      util.cache_put('remind_self_lift', e.detail);
    }
    setData['isShowSelfLiftingPopup'] = false;
    setData['isRemind'] = e.detail;
    if(self.data.requestDiscount.dispatchType === 1){
      setData['isSelectPickupName'] = true;
    }else{
      setData['isSelectAddress'] = true;
    }
    self.setData(setData);
    this.paySubmit();
  },
});
